﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.UI.
using Telerik.Web.UI;
using KPIS.Utils;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.APP.Classes;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class ViView : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private IPositionBLL posBLL = new PositionBLL();
        private IEmployeeTypeBLL emptypeBLL = new EmployeeTypeBLL();
        private PositionExtraBLL extBLL = new PositionExtraBLL();
        private HRMKeyPerformanceAreaListBLL cmd = new HRMKeyPerformanceAreaListBLL();
        private SsMng creatby = new SsMng();
        private Main main = new Main();

        private int idJobSiteSeqRoot = 1;//ฝั่งโครงสร้างตามกฎกระทรวง

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                FillDataToEmpType();
                txtSearch.Text = "";
                lbnAddNew.Visible = false;
            }

        }

        public void FillDataToEmpType()
        {
            IList<EmployeeTypeInfo> InfoList = emptypeBLL.ListEmployeeTypes(null);

            cmbEmpType.DataSource = InfoList;
            cmbEmpType.DataBind();
        }

        protected void imbSearch_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeNodeCollection nodes = this.RadTreeView.Nodes;
            string strSearch = txtSearch.Text.TrimEnd();

            foreach (RadTreeNode n in nodes)
            {
                n.BackColor = RadTreeView.BackColor;
                main.ClearRecursive(n, RadTreeView.BackColor);
            }

            foreach (RadTreeNode n in nodes)
            {
                if (strSearch.Length > 0)
                {
                    if (n.Text.IndexOf(strSearch) >= 0)
                    {
                        n.BackColor = System.Drawing.Color.Yellow;
                        n.ExpandParentNodes();
                    }
                    main.FindRecursive(n, strSearch);
                }
            }
        }

        protected void RadTreeView_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            RadTreeNode selected_node = RadTreeView.SelectedNode;
            string strValue = selected_node.Value;
            EnableControl(false);

            string[] root_value = strValue.Split(new string[] { "-" }, StringSplitOptions.None);
            int intCount = root_value.Length;
            Session["TreeNodeValue"] = strValue;
            Session["TreeNodeSelect"] = strValue;
            if (!string.IsNullOrEmpty(strValue))
            {
                if (intCount > 1)
                {
                    Session["TreeNodeValue"] = root_value[1];
                    Session["POS_SEQ"] = Session["TreeNodeValue"].ToString().Trim();
                    OnUpdateCmdUI("VIEW");
                    lbnAddNew.Visible = true;
                    ltrMessageError.Visible = true;
                }
                else
                {
                    OnUpdateCmdUI("");
                    ltrMessageError.Visible = false;
                }
            }
        }

        protected void cmbEmpType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Session["EMP_TYPE_SEQ"] = cmbEmpType.SelectedValue;
            LoadRootNodes(RadTreeView, TreeNodeExpandMode.ServerSideCallBack);
            lbnAddNew.Visible = false;
            if (RadGridKeyArea.Visible == true )
            {
               OnUpdateCmdUI("HIDE");
            }
            ltrMessageError.Visible = false;
        }

        private void LoadDetail()
        {
            int Sequence = Session["TreeNodeValue"].ToString().Length > 0 ? Int32.Parse(Session["TreeNodeValue"].ToString()) : idJobSiteSeqRoot;
            DataSet ds = posBLL.LoadPositions(Sequence, (int?)null, (int?)null, "");

            DataRowCollection drc;

            if (ds.Tables.Count > 0)
            {
                drc = ds.Tables[0].Rows;
                if (drc.Count > 0)
                {
                    EnableControl(true);

                    txtPositionName.Text = drc[0]["POS_NAME"].ToString();

                    int intPosSeq = Convert.ToInt32(drc[0]["POS_SEQ"]);
                    LoadDataGrid(intPosSeq);
                }
                 
            }
            
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["update"] = Session["update"];
        }

        private void OnUpdateCmdUI(string strMode)
        {
            bool blnViewMode = strMode == "VIEW";
            bool blnHideMode = strMode == "HIDE";
            bool blnNull = strMode == "";

            if (blnViewMode)
            {
                LoadDetail();
            }

            if (blnHideMode)
            {
                EnableControl(false);
            }

        } 

        private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            //IList<TreeViewInfo> infoList = treeBLL.LoadJobSiteAreaTreeView("");
            Nullable<int> intEmpTypeSeq = cmbEmpType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmpType.SelectedValue) : (int?)null;

            treeView.Nodes.Clear();

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(intEmpTypeSeq, ""))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;//  info.Id.Split('-').Count() > 1 ? info.Name : String.Format("{0} : {1}", info.Id, info.Name);
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }
        }

        private void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();

            Nullable<int> intEmpType = string.IsNullOrEmpty(cmbEmpType.SelectedValue) ? (int?)null : Int32.Parse(cmbEmpType.SelectedValue);

            int childNode = 0;

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(intEmpType, e.Node.Value))// treeBLL.LoadJobSiteAreaTreeView(e.Node.Value))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name; // info.Id.Split('-').Count() > 1 ? info.Name : String.Format("{0} : {1}", info.Id, info.Name);
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                childNode = info.Children_count;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }
            if (childNode > 0)
            {
                e.Node.Expanded = true;
                e.Node.ExpandMode = expandMode;
            }
        }

        protected void RadTreeView_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);

        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            OnUpdateCmdUI("ADDNEW");

            string strUrl = string.Format("HRMKeyPerformanceAreaList_POP.aspx?PosSeq={0}", Session["POS_SEQ"].ToString() + "&Mode=" + "AddNew");
            RadAjaxManager.GetCurrent(Page).ResponseScripts.Add(String.Format("radopen('{0}', '{1}');", strUrl, "POP"));
        }

        public void LoadDataGrid(int pos_seq)
        {
            var ds = cmd.LoadGridKeyArea(pos_seq);
            try
            {
                ltrMessageError.Text = "น้ำหนักต้องรวมได้ 100% จึงจะสามารถทำการประเมินได้ ปัจจุบันมี " +(from DataRow dr in ds.Rows select Convert.ToInt32(dr["weight"])).Sum().ToString();
                ltrMessageError.Visible = true;
            }
            catch
            {
                ltrMessageError.Text = "";}
            RadGridKeyArea.DataSource = ds;
            RadGridKeyArea.DataBind();
        }

        protected void RefreshGridKeyArea()
        {
            int intPosSeq = Convert.ToInt32(Session["POS_SEQ"]);
            var ds = cmd.LoadGridKeyArea(intPosSeq);

            try
            {
                ltrMessageError.Text = "น้ำหนักต้องรวมได้ 100% จึงจะสามารถทำการประเมินได้ ปัจจุบันมี " + (from DataRow dr in ds.Rows select Convert.ToInt32(dr["weight"])).Sum().ToString();
                ltrMessageError.Visible = true;
                
            }
            catch
            {
                ltrMessageError.Text = "";
            }
            RadGridKeyArea.DataSource = ds;
            RadGridKeyArea.DataBind();
        }

        protected void RadManager1_AjaxReQuest(object sender, AjaxRequestEventArgs e)
        {
            RefreshGridKeyArea();
        }

        protected void RadGridKeyArea_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "btnDelete")
            {
                int intKpaSeq =Convert.ToInt32((e.Item as GridDataItem).GetDataKeyValue("kpa_seq"));
                cmd.DeleteKeyArea(intKpaSeq, creatby.EmpSeq);
                RefreshGridKeyArea();
            }
        }

        protected void EnableControl(bool blnLogic)
        {
            txtPosition.Visible = blnLogic;
            txtPositionName.Visible = blnLogic;
            lbnAddNew.Enabled = blnLogic;
            RadGridKeyArea.Visible = blnLogic;
        }

        

    }
}
